package base_init

import (
	"context"
	"github.com/redis/go-redis/v9"
	"go-likaladi-shop/common/base_config"
	"go-likaladi-shop/common/base_global"
	"go.uber.org/zap"
	"time"
)

func RedisConfig(redisConfig base_config.RedisConfig) {
	conf := redisConfig.Cluster
	base_global.RdbCluster = redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:          conf.Addrs,
		Username:       conf.Username,
		Password:       conf.Password,
		PoolSize:       conf.PoolSize,
		ReadOnly:       conf.ReadOnly,
		RouteByLatency: conf.RouteByLatency,
		RouteRandomly:  conf.RouteRandomly,
		DialTimeout:    time.Duration(conf.DialTimeout) * time.Second,
		ReadTimeout:    time.Duration(conf.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(conf.WriteTimeout) * time.Second,
	})

	// 测试 ping
	pong, err := base_global.RdbCluster.Ping(context.Background()).Result()
	if err != nil {
		//panic(fmt.Errorf("❌ Redis Cluster 连接失败: %v", err))
		//zap.S().Fatalf()（会直接 os.Exit(1)，直接退出, 适合初始化）
		zap.S().Fatalf("❌ Redis Cluster 连接失败: %v", err)
	}
	zap.S().Infof("✅ Redis Cluster 连接成功: %s", pong)
}
